//
//  HistoryViewController.swift
//  app路由
//
//  Created by zhaoguoteng on 2020/4/27.
//  Copyright © 2020 zhaoguoteng. All rights reserved.
//

import UIKit
import FMDB

class HistoryViewController: UIViewController {

    @IBOutlet var tableView: UITableView!

    var dataList = [History]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        loadDBData()
    }
    
    func setupView() {
    }
}

/// db handle
extension HistoryViewController {
    
    func loadDBData() {
        
        SqliteManager.queryData(sql: "select * from scanlog order by date DESC",
                                result: { [weak self] (res: [History]) in
                                    
                                    guard let self = self else {
                                        return
                                    }    
                                    self.dataList = res
                                    self.tableView.reloadData()
        })
    }
    
    /// 清除
    @IBAction func clearAction() {
     
        let alert = UIAlertController(title: "清除历史", message: nil, preferredStyle: .actionSheet)
        
        alert.addAction(UIAlertAction(title: "清除全部", style: .destructive, handler: { [weak self] _ in
            
            guard let self = self else {
                return
            }
            
            guard let db = SqliteManager.shareDB else {
                return
            }
            
            if !db.isOpen {
                db.open()
            }
            
            do {
                try db.executeUpdate("delete from scanlog", values: nil)
                self.loadDBData()
            } catch {
                fatalError(error.localizedDescription)
            }
            
            db.close()
        }))
        
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        
        present(alert, animated: true, completion: nil)
    }
}

extension HistoryViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HistoryCell", for: indexPath)
        
        let history = dataList[indexPath.row]
        
        if let label = cell.viewWithTag(10) as? UILabel {
            label.text = history.json
        }
        
        if let label = cell.viewWithTag(11) as? UILabel {
            
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            if let date = history.date {
                label.text = dateFormatter.string(from: date)
            } else {
                label.text = nil
            }
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let history = dataList[indexPath.row]
        
        guard let json = history.json else {
            return
        }
        
        let alert = UIAlertController(title: "重新添加结果", message: json, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "取消", style: .destructive, handler: nil))
        alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { [weak self] (_) in
            
            guard let self = self else {
                return
            }
            
            let jsonData = json.data(using: .utf8)
            let list = Route.routes(jsonData: jsonData)
            self.save(list: list)
            self.navigationController?.popViewController(animated: true)
        }))
        
        present(alert, animated: true, completion: nil)
    }
    
    func save(list: [Route]?) {
        
        guard let db = SqliteManager.shareDB else {
            return
        }
        
        if !db.isOpen {
            db.open()
        }
        
        if let list = list {
            db.beginTransaction()
            for route in list {
                guard let name = route.name, let url = route.url else {
                    print("数据不完整")
                    return
                }
                
                do {
                    try db.executeUpdate("insert into routes (name, url, date) values ('\(name)', '\(url)', '\(Date().timeIntervalSince1970)')", values: nil)
                } catch {
                    fatalError(error.localizedDescription)
                }
            }
            db.commit()
        }
        
        db.close()
    }
}
